# -*- coding: utf-8 -*-
'''
@author: Script Team
@Created on: 2011-7-29
@version: 2011.7.29
@summary: Definition of Runner class
'''
import time, os
import Queue
from threading import Thread
from  core import CoreTest


def main():
    runner = Runner()
    runner.TestRunner('Test Server')


class Runner(Thread):
    '''
    Create and start Test object. 
    Act as a thread and get job from work queue.
    '''
    timeout = 1
    
    def __init__(self, workQueue, host, destination, parent = None):
        '''
        Constructor.
        Keyword arguments:
        workQueue -- all test job queue
        host -- test host information, e.g. [localhost,4445,*chrome]
        server -- test server, such as 'Test Server'
        time_stamp -- timestamp for this thread
        '''
        Thread.__init__(self)
        self.host = host[0]
        self.port = host[1]
        self.browser = host[2]
        self.workQueue = workQueue
        self.dataList = ()
        self.destination = destination
        self.start()

    def run(self):
        '''
        Execute when start of Runner object is called. 
        Create Test object and prepare test steps.
        '''
        self.core = CoreTest()

        self.core.setUp(self.host, self.port, self.browser, self.destination)
#        request = urllib2.Request(server_link)
#        request.add_header('Cache-Control', 'no-cache')
        
        # Get test job from work queue while queue is not empty
        while True:
            try:
                dest, cases = self.workQueue.get(timeout = Runner.timeout)
                print 'runner -- dest url: ' + dest
                self.TestRunner(cases)
            except Queue.Empty:
                self.core.tearDown()
                self.core.shutDownServer()
                break
        
            
    def TestRunner(self, cases):
        '''
        Reorganize test data and start test.
        Keyword arguments:
        host -- test host, e.g. localhost
        port -- test port, e.g. 4444
        browser -- test browser, e.g. *chrome
        server -- test server, such as 'Test Server'
        steps -- steps to be tested
        '''
        message = self.core.test(cases)
            
        time.sleep(3)

    
if __name__ == "__main__":
    main()